/*
 * @Author: yangzonglong
 * @Date: 2020-06-15 14:07:19
 * @version: v1.0.0
 * @Descripttion:
 * @LastEditors: yangzonglong
 * @LastEditTime: 2021-09-23 18:08:27
 * @Auditor:
 */
import server from './../../utils/server/server';

const _caches = {};

type OptionsProps = {
  url: string;
  query: object;
  cacheKey?: string;
  rtnDataAfter?: Function;
};

export async function getData({ url, query, cacheKey, rtnDataAfter }: OptionsProps, callback: Function) {
  try {
    if (cacheKey) {
      if (!_caches[cacheKey]) _caches[cacheKey] = {};

      if (_caches[cacheKey].inRequest) {
        if (_caches[cacheKey].data) return callback(_caches[cacheKey].data);
        else return _caches[cacheKey].callbacks.push(callback);
      }

      _caches[cacheKey].inRequest = true;
      _caches[cacheKey].callbacks = [callback];
    }

    const result = await server(url, query);
    const rows = rtnDataAfter ? rtnDataAfter(result) : result.rows || result;

    if (cacheKey) {
      _caches[cacheKey].callbacks.forEach((fn: Function) => fn(rows));
      _caches[cacheKey].data = rows;
      _caches[cacheKey].callbacks = [];
    } else {
      callback(rows);
    }
  } catch (error) {
    if (cacheKey) {
      _caches[cacheKey].callbacks = [];
    } else {
      callback([]);
    }
  }
}
